import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Cookie } from 'ng2-cookies';
import { AppConsts } from './consts';
import { User } from './_model/user';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class Functions {
  constructor(
    private _consts: AppConsts) { }

  getRequestOptions(): RequestOptions {
    const token = Cookie.get(this._consts.authCookieName);
    const headers = new Headers({ 'Authorization': `Bearer ${token}` });
    const options = new RequestOptions({ headers });
    return options;
  }

  getCurrentUser(): User {
    return JSON.parse(localStorage.getItem(this._consts.userLocalstorageName)) as User;
  }

  isDefaultIcon(icon): boolean {
    return this._consts.defaultIcons.includes(icon);
  }

  handleHttpError(error: Response | any) {
    if (error._body) {
      const err = error.json();
      return Observable.throw(err);
    }
    const msg = error.message ? error.message : error.toString();
    return Observable.throw({msg});
  }
}
